package com.quran.db;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.tos.quran.QuranActivity;
import com.tos.quran.QuranApp;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper {

	public static final int CURRENT_DATABASE_STRUCTURE_FIRST_VERSION = 2;
	
	
	public static final String DATABSE_FILE_FOLDER_NAME = "db/";

	public static final int DB_VERSION = 2;

	private Context context;

	private SQLiteDatabase myDataBase;

	private static final String DATABSE_FILE_FORMAT = "qdb%d.db";
	public static final Pattern DATABSE_FILE_PATTERN = Pattern
			.compile("qdb([0-9]+).db");

	public DatabaseHelper(Context context) {
		super(context, getFileName(context), null, getVersionNo(context));
		this.context = context;
	}

	private static String getFileName(Context context) {
		return ((QuranApp) context.getApplicationContext()).isOnSdCard() ? context
				.getDatabasePath(getDBName(context)).getAbsolutePath()
				: getDBName(context);
	}

	private static String getDBName(Context context) {
		
		
		return String.format(Locale.ENGLISH, DATABSE_FILE_FORMAT, getVersionNo(context));
	}
	private static String getDBName(int version) {
		return String.format(Locale.ENGLISH, DATABSE_FILE_FORMAT, version);
	}

	private static int getVersionNo(Context context) {
		return DB_VERSION;
	}

	public void openDataBase() throws SQLException {
		myDataBase = SQLiteDatabase.openDatabase(
				context.getDatabasePath(getDBName(context)).getAbsolutePath(),
				null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
	}

	public synchronized void close() {
		if (myDataBase != null) {
			myDataBase.close();
		}
		super.close();
	}

	public void onCreate(SQLiteDatabase db) {
	}

	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
	}
	public static boolean databaseFileExists(Context context) {
		boolean ret = false;
		try {
			ret = context.getDatabasePath(getDBName(context)).exists();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ret;
	}
	
	public static boolean updateDatabaseFile(Context context,int version) {
		boolean ret = false;
		try {
			ret = context.getDatabasePath(getDBName(version)).renameTo(context.getDatabasePath(getDBName(context)));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ret;
	}
	public static boolean deleteDatabaseFile(Context context,int version) {
		boolean ret = false;
		try {
			ret = context.getDatabasePath(getDBName(version)).delete();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ret;
	}

	public static boolean deleteDatabaseFile(Context context) {
		boolean ret = false;
		try {
			ret = context.getDatabasePath(getDBName(context)).delete();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ret;
	}

	public static int getExistingDatabaseFileVersion(QuranActivity context) {
		int ret = -1;
		try {
			final String databaseFileName = getDBName(context);
			final File databaseFile = context.getDatabasePath(databaseFileName);
			final File parentFile = databaseFile.getParentFile();

			if (parentFile.exists() && parentFile.isDirectory()) {
				File[] files = parentFile.listFiles();
				if (files != null) {
					for (int i = 0; i < files.length; i++) {
						File file = files[i];
						if (file.isFile()) {
							String fileName = file.getName();
							Matcher m = DATABSE_FILE_PATTERN.matcher(fileName);
							if(m.find()){
								ret = Integer.parseInt(m.group(1))  ;
								break;
							}
						}
					}
				}

			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return ret;
	}

	public static void manageDatabase(QuranActivity context,
			boolean forceDeletePrevious) {
		try {

			final String databaseFileName = getDBName(context);
			final File databaseFile = context.getDatabasePath(databaseFileName);
			final File parentFile = databaseFile.getParentFile();

			if (parentFile.exists()) {
				if (parentFile.isDirectory()) {
					File[] files = parentFile.listFiles();
					if (files != null && files.length > 0) {
						for (int i = 0; i < files.length; i++) {

							File file = files[i];
							if (file.isFile()) {
								String fileName = file.getName();
								if ((!fileName.equals(databaseFileName))
										&& DATABSE_FILE_PATTERN.matcher(
												fileName).find()) {
										files[i].delete();
								}
							}
						}
					}
				} else {
					parentFile.delete();
					parentFile.mkdirs();
				}
			} else {
				parentFile.mkdirs();
			}
			boolean exists = databaseFile.exists();
			try {
				if (forceDeletePrevious && exists) {
					databaseFile.delete();
					exists = false;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (!exists) {
				OutputStream myOutput = new FileOutputStream(databaseFile);
				byte[] buffer = new byte[1024];
				int length;

				final String[] FILE_PARTS = context.getAssets().list("db");
				Arrays.sort(FILE_PARTS);
				for (int i = 0; i < FILE_PARTS.length; i++) {
					InputStream myInput = context.getAssets().open(
							DATABSE_FILE_FOLDER_NAME + FILE_PARTS[i]);
					while ((length = myInput.read(buffer)) > 0) {
						myOutput.write(buffer, 0, length);
					}
					myInput.close();
				}
				myOutput.flush();
				myOutput.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
